{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最优解的顺序: [5 3 8 2 7 9 6 4 1 0]\n",
      "最优解的总距离: 3.220686155231152\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "def distance(city1, city2):\n",
    "    return np.linalg.norm(city1 - city2)\n",
    "\n",
    "def total_distance(order, cities):\n",
    "    total = 0\n",
    "    for i in range(len(order) - 1):\n",
    "        total += distance(cities[order[i]], cities[order[i + 1]])\n",
    "    return total + distance(cities[order[-1]], cities[order[0]])\n",
    "\n",
    "def simulated_annealing(cities, initial_order, temperature, cooling_rate):\n",
    "    current_order = initial_order\n",
    "    best_order = current_order\n",
    "    while temperature > 1e-5:\n",
    "        new_order = np.random.permutation(current_order)\n",
    "        current_distance = total_distance(current_order, cities)\n",
    "        new_distance = total_distance(new_order, cities)\n",
    "        if new_distance < current_distance or np.random.rand() < np.exp((current_distance - new_distance) / temperature):\n",
    "            current_order = new_order\n",
    "        if total_distance(current_order, cities) < total_distance(best_order, cities):\n",
    "            best_order = current_order\n",
    "        temperature *= cooling_rate\n",
    "    return best_order\n",
    "\n",
    "# 示例\n",
    "np.random.seed(42)\n",
    "num_cities = 10\n",
    "cities = np.random.rand(num_cities, 2)\n",
    "initial_order = np.arange(num_cities)\n",
    "np.random.shuffle(initial_order)\n",
    "\n",
    "final_order = simulated_annealing(cities, initial_order, temperature=1000, cooling_rate=0.995)\n",
    "print(\"最优解的顺序:\", final_order)\n",
    "print(\"最优解的总距离:\", total_distance(final_order, cities))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
